<template>
  <div class="container">
    <logoTop class="topLogo" />
    <div id="mapContainer"></div>
    <baseLayerTabs @sl="sl"  class="baseLayer" @sllayeradd="sllayeradd" v-show="baseLayerShow"/>
    <popView ref="popView" class="popView"/>
    <div class="person">
      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
          <i class="el-icon-caret-bottom" />
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item divided @click.native="loginOut">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div  class="search-box-component">
      <div id="searchBoxComponent"  class="search-box">
        <el-select
            v-model="keyWords"
            filterable
            remote
            @change="change"
            reserve-keyword
            placeholder=""
            :remote-method="remoteMethod"
            :loading="loading">
          <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            <span style="float: left">{{ item.text }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.startDate }}---{{ item.endDate}}</span>
<!--            <span style="width:50px;height: 200px;overflow: hidden;padding: 10px;"  v-html="item.content"></span>-->
          </el-option>
        </el-select>
        <div class="icon icon-logo iconLogo"></div>
        <div class="icon icon-search"></div>
      </div>
    </div>
    <el-image
        style="height: 35px"
        :src="layerurl"
        class="tclayer"
        @click="layerClick"
        fit="fill"></el-image>
    <el-image
        style="height: 30px"
        :src="timeurl"
        class="timelayer"
        fit="fill"
        @click="timeClick"></el-image>
    <leftMenu ref="leftMenu" @quit3D="quit3D" class="leftMenu" @addNode="addNode" @removeNode="removeNode"/>
    <timeLine class="timeline" v-if="timelineState"  @timeclick="timeclick" @timeChange="timeChange" @upDataTime="upDataTime"/>
  </div>
</template>

<script>
import {
  add3Dtiles, add3Dtilesforarray,
  addGdsllayer,
  addLayersfor3d,
  addPoint,
  addTianlayer, appendRoads, appendditie, addPoipoint, addGeojson,
  initEarth, initHight, loadTilesShader, add2dLayers
} from "@/api/CesiumUtils";
import {getBytime, getList} from "@/api/login";
import * as Cesium from "cesium/Source/Cesium";
import logoTop from "@/components/logoTop/logoTop";
import baseLayerTabs from "@/components/BaseLayer/baseLayerTabs";
import popView from "@/components/popView/popView";
import Cookies from 'js-cookie'
const TokenKey = 'Admin-Token'
import layersManger from '@/components/layersmanager/layersmanger'
import timeLine from '@/components/timeLine/timeLine'
import leftMenu from "@/components/leftMenu/leftMenu";
export default {
  name: "mapView",
  data(){
    return{
      url:require('./assets/images/logo.jpg'),
      layerurl:require('./assets/images/图层 .png'),
      imgageProvider:null,
      cesium3dtiles:null,
      timeurl:require('./assets/images/time.png'),
      baseLayerShow:true,
      levelInfo:'',
      // 三维视野内模型
      cesium3dtilesArray:[],
      // 所有得三维数据
      layerslist3d:[],
      modellist:[],
      timelineState:false,
      options: [],
      value: [],
      list: [],
      loading: false,
      keyWords:''
    }
  },
  components:{
    logoTop,
    baseLayerTabs,
    popView,
    // layersManger,
    timeLine,
    leftMenu
  },
  mounted() {
    window.viewer = initEarth("mapContainer",Cesium);
    // this.jundgeModelinTime()
    let self = this;
    let handler = new Cesium.ScreenSpaceEventHandler(window.viewer.scene.canvas);





    this.getListpoint()

    console.log(this.getCesiumViewerExtend())



    //鼠标移动监听，插件跟踪
    handler.setInputAction(() => {
      let openArea = self.getCesiumViewerExtend();
      //判断当前模型是不是 在视图区域内
      self.modellist.forEach((modelitem)=>{
        // if(modelitem.lon <=openArea.maxx && modelitem.lon >=openArea.minx && modelitem.lat <= openArea.maxy && modelitem.lat >= openArea.miny){
        //   modelitem.model.show = true;
        // }else {
        //   modelitem.model.show = false;
        // }
      })
    }, Cesium.ScreenSpaceEventType.WHEEL);


    handler.setInputAction(function (e) {
      var pick = window.viewer.scene.pick(e.position);
      if (pick&&pick.id) {
        console.log(pick.id._id)
        self.layerslist3d.forEach((ite)=>{
          if(ite.id == pick.id._id){
            self.$refs.popView.tabCardShow = true;
            self.$refs.popView.title = ite.text;
            self.$refs.popView.content = ite.content
          }
        })
      }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    // 左键弹起事件
    handler.setInputAction((e) => {
      var pick = window.viewer.scene.pick(e.position);
      if (pick&&pick.id) {
        console.log(pick.id._id)
        self.layerslist3d.forEach((ite)=>{
          if(ite.id == pick.id._id){
            self.$refs.popView.tabCardShow = true;
            self.$refs.popView.title = ite.text;
            self.$refs.popView.content = ite.content
          }
        })
      }
      let openArea = self.getCesiumViewerExtend();
      //判断当前模型是不是 在视图区域内
      self.modellist.forEach((modelitem)=>{
        // if(modelitem.lon <=openArea.maxx && modelitem.lon >=openArea.minx && modelitem.lat <= openArea.maxy && modelitem.lat >= openArea.miny){
        //
        //   modelitem.model.show = true;
        // }else {
        //   modelitem.model.show = false;
        // }
      })
    }, Cesium.ScreenSpaceEventType.LEFT_UP);


  },
  methods:{
    addNode(node){
      // eslint-disable-next-line no-prototype-builtins
      if(!node.hasOwnProperty('nodes')){
        console.log("添加",node);
        this.layeritemClick(node,true)
      }
    },
    removeNode(node){
      // eslint-disable-next-line no-prototype-builtins
      if(!node.hasOwnProperty('nodes')){
        console.log("移除",node)
        this.layeritemClick(node,false)
      }
    },
    quit3D(){
      // window.viewer.dataSources.removeAll(); //移除
      // window.viewer.scene.primitives.removeAll();
      // this.getListpoint()
      window.viewer.camera.setView({
        destination:Cesium.Cartesian3.fromDegrees(116.29758183, 39.98561288, 1000),
        orientation:{
          // 指向
          heading:Cesium.Math.toRadians(0,0),
          // 视角
          pitch:Cesium.Math.toRadians(-90),
          roll:0.0
        }
      });
    },

    getListpoint(){
      //请求所有得列表数据
      window.viewer.camera.setView({
        destination:Cesium.Cartesian3.fromDegrees(116.29758183, 39.98561288, 1000),
        orientation:{
          // 指向
          heading:Cesium.Math.toRadians(0,0),
          // 视角
          pitch:Cesium.Math.toRadians(-90),
          roll:0.0
        }
      });
      getList({
        type: 0
      }).then((res)=>{
        this.layerslist3d = res.rows;
        //视野范围内所有添加所有的模型
        let temp = add3Dtilesforarray (Cesium,window.viewer,this.layerslist3d);
        this.modellist = temp;
      })
    },
    remoteMethod(query) {
      console.log(query)
      if (query !== '') {
        this.loading = true;
        getList({
          pageNum:1,
          ageSize:10,
          text:query
        }).then((res)=>{
          console.log(res)
          this.loading = false;
          this.options = res.rows;
        })

      } else {
        this.options = [];
      }
    },
    change(node){
      console.log(node);
      let result =  this.options.filter((ite)=>{
        return ite.id == node;
      })
      console.log(result)
      window.viewer.camera.setView({
            destination:Cesium.Cartesian3.fromDegrees(Number(result[0].longitude), Number(result[0].dimension) - 0.001, 75),
            orientation:{
              // 指向
              heading:Cesium.Math.toRadians(0,0),
              // 视角
              pitch:Cesium.Math.toRadians(-30),
              roll:0.0
            }
      })
    },
    layeritemClick(o,status){
      debugger
      // eslint-disable-next-line no-prototype-builtins
      if(window.hasOwnProperty('imagesLayer')){
        window.viewer.scene.imageryLayers.remove(window.imagesLayer);
      }
      switch (o.methods) {
        case 'loadTilesShader':
            loadTilesShader(Cesium,window.viewer,o,status)
            break;
        case 'appendRoads':
            appendRoads(Cesium,window.viewer,o,status)
            break
        case 'appendditie':
            appendditie(Cesium,window.viewer,o,status)
            break
        case "addPoipoint":
           addPoipoint(Cesium,window.viewer,status)
            break
        case "addGeojson":
            addGeojson(Cesium,window.viewer,o,status)
            break
        case 'add2dLayers':
            window.imagesLayer =  add2dLayers(Cesium,window.viewer,o);
            break
      }
      window.viewer.camera.setView({
        destination:Cesium.Cartesian3.fromDegrees(Number(o.lon), Number(o.lat), 3500),
        orientation:{
          // 指向
          heading:Cesium.Math.toRadians(0,0),
          // 视角
          pitch:Cesium.Math.toRadians(-30),
          roll:0.0
        }
      });
    },
    layerClick(){
      // window.viewer.entities.removeAll();
      // 图层管理器
      this.$refs.leftMenu.state = true;
    },
    //获取当前得视野范围
    getCesiumViewerExtend() {
      window.cesiumViewer  = window.viewer;
      let params = {};
      let extend = window.cesiumViewer.camera.computeViewRectangle();
      if (typeof extend === "undefined") {
        //2D下会可能拾取不到坐标，extend返回undefined,所以做以下转换
        let canvas = window.cesiumViewer.scene.canvas;
        let upperLeft = new Cesium.Cartesian2(0, 0); //canvas左上角坐标转2d坐标
        let lowerRight = new Cesium.Cartesian2(canvas.clientWidth, canvas.clientHeight); //canvas右下角坐标转2d坐标

        let ellipsoid = window.cesiumViewer.scene.globe.ellipsoid;
        let upperLeft3 = window.cesiumViewer.camera.pickEllipsoid(upperLeft, ellipsoid); //2D转3D世界坐标

        let lowerRight3 = window.cesiumViewer.camera.pickEllipsoid(lowerRight, ellipsoid); //2D转3D世界坐标

        let upperLeftCartographic = window.cesiumViewer.scene.globe.ellipsoid.cartesianToCartographic(upperLeft3); //3D世界坐标转弧度
        let lowerRightCartographic = window.cesiumViewer.scene.globe.ellipsoid.cartesianToCartographic(lowerRight3); //3D世界坐标转弧度

        let minx = Cesium.Math.toDegrees(upperLeftCartographic.longitude); //弧度转经纬度
        let maxx = Cesium.Math.toDegrees(lowerRightCartographic.longitude); //弧度转经纬度

        let miny = Cesium.Math.toDegrees(lowerRightCartographic.latitude); //弧度转经纬度
        let maxy = Cesium.Math.toDegrees(upperLeftCartographic.latitude); //弧度转经纬度


        params.minx = minx;
        params.maxx = maxx;
        params.miny = miny;
        params.maxy = maxy;
      } else {
        //3D获取方式
        params.maxx = Cesium.Math.toDegrees(extend.east);
        params.maxy = Cesium.Math.toDegrees(extend.north);

        params.minx = Cesium.Math.toDegrees(extend.west);
        params.miny = Cesium.Math.toDegrees(extend.south);
      }
      console.log(params)
      return params; //返回屏幕所在经纬度范围
    },

    //当前视野范围模型的时间序列事件
    jundgeModelinTime(modelid,startTime,endTime){
      getList({
        startDate:'1684-01-01',
        endDate:'1900-01-01'
      }).then((res)=>{
        console.log(res)
      })
    },

    upDataTime(begin,end){
      let beginData = `${begin.slice(0,4)}`;
      let endData = `${end.slice(0,4)}`;
      console.log(beginData,endData);
      getBytime(beginData,endData).then((res)=>{
        console.log("事件筛选",res)
        this.modellist.forEach((item)=>{
          // item.model.show = false;
          res.rows.forEach((ite)=>{
            if (item.id == ite.id){
              item.model.show  = true
            }else{
              item.model.show  = false
            }
          })
        })
      })
    },

    timeChange(res){
      console.log(res)
      this.modellist.forEach((item)=>{
        item.model.show = false;
        res.rows.forEach((ite)=>{
          if (item.id == ite.id){
            item.model.show  = true
          }else{
            item.model.show  = false
          }
        })
      })
    },





















    sllayeradd(){
      if(this.imgageProvider){
        window.viewer.imageryLayers.remove(this.imgageProvider);
      }
      this.imgageProvider = addTianlayer(Cesium,window.viewer)
    },
    sl(){
      if(this.imgageProvider){
        window.viewer.imageryLayers.remove(this.imgageProvider);
      }
      this.imgageProvider = addGdsllayer(Cesium,window.viewer)
    },
    loginOut(){
      let self =  this;
      Cookies.remove(TokenKey)
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.$router.push({
          path:'/login'
        })
      }).catch(() => {});
    },
    timeclick(val){
      console.log(val)
    },
    timeClick(){
      this.$refs.popView.tabCardShow = false;
      this.baseLayerShow = false;
      this.timelineState = !this.timelineState
    }
  }
}
</script>

<style lang="scss" scoped>
//116.233109  39.991874
.container{
  width: 100%;
  height: 100%;
  .topLogo{
    position: absolute;
    top: 1rem;
    left: 1rem;
    z-index: 99;
  }

  .popView{
    position: absolute;
    top: 5rem;
    right: 2rem;
    z-index: 99;
  }
}
::v-deep .navigation-controls{
  z-index: 99;
  position: absolute;
  top: 85%;
  right: 10px;
}
::v-deep .navigation-control-icon-reset{
  position: absolute;
}
.baseLayer{
  position: absolute;
  top: 90%;
  right: 70px;
}
.timeline{
  position:absolute;
  bottom:75px;
  z-index: 99;
}
.person{
  position: absolute;
  top: 1rem;
  right: 2rem;
  z-index: 99;
}
.tclayer{
  position: absolute;
  top: 1.5rem;
  right: 6.5rem;
  z-index: 99;
}
.leftMenu{
  position: absolute;
  top: 5rem;
  left: 1rem;
  z-index: 99;
}
.timelayer{
  position: absolute;
  top: 1.5rem;
  right: 9.5rem;
  z-index: 99;
}
#mapContainer{
  width: 100%;
  height: 100%;
}
::v-deep .cesium-widget, .cesium-widget canvas{
  height: 100vh;
}
.search-box-component .search-box {
  display: block;
  margin-top: 0;
  width: 100%;
  height: 100%;
  transition: all .3s ease;
  position: relative;
  z-index: auto;
  border-radius: 2px;
}
.search-box-component .search-box .icon-logo {
  position: absolute;
  top: 0;
  left: 5px;
  width: 24px;
  height: 40px;
  background: url('https://static.allhistory.com/online/view/Map/img/logo.1598.svg') no-repeat 50%;
  background-size: contain;
  cursor: pointer;
}
.search-box-component .search-box .icon-search {
  position: absolute;
  top: 10px;
  right: 5px;
  width: 20px;
  height: 20px;
  background: url('https://static.allhistory.com/online/view/Map/img/search-icon.304c.svg') no-repeat 50%;
  background-size: contain;
  cursor: pointer;
}
.search-box-component {
  display: block;
  position: absolute;
  top: 1.5rem;
  right: 12.5rem;
  z-index: 99;
  height: 35px;
}
::v-deep .el-input__inner{
  padding:0 40px!important;
}
::v-deep .el-select-dropdown__item{
  height: 200px;
  //::v-deep  p{
  //  width: 50px !important;
  //}
}
</style>
